package com.yfuxdeer.youchat.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.ui.fragment.RegisterStep2;
import com.yfuxdeer.youchat.utils.CodeUtil;
import com.yfuxdeer.youchat.utils.KeyBoardUtil;

import java.util.Random;
import java.util.regex.Pattern;

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private EditText phone;
    private EditText checkCode;
    private Button sendCode;
    private Button next;
    private Button cancel;
    private int time = 120;
    private String phone_;
    private String realCheckCode = "000000";
    private boolean outdated = false;
    private Handler handler = new Handler();

    public String getPhone_() {
        return phone_;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        findViews();
        setListeners();
    }

    private void setListeners() {
        phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    KeyBoardUtil.closeKeyboard(view);
                }
            }
        });
        checkCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    KeyBoardUtil.closeKeyboard(view);
                }
            }
        });
        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                phone_ = phone.getText().toString();
                if (!validatePhone(phone_) && !validateEmail(phone_)) {
                    Toast.makeText(getApplicationContext(), "请输入手机号或邮箱", Toast.LENGTH_SHORT).show();
                    return;
                } else if (validatePhone(phone_)) {
                    // 发送手机验证码
                    realCheckCode = generateCode();
                    CodeUtil.sendCheckCodeToPhone(phone_, realCheckCode);
                } else {
                    //发送邮箱验证码
                    Log.e(TAG, "发送邮箱: " + phone_);
                    realCheckCode = generateCode();
                    CodeUtil.sendCheckCodeToEmail(phone_, realCheckCode);
                }
                outdated = false;
                Log.e(TAG, "验证码为 : " + realCheckCode);
                Toast.makeText(getApplicationContext(), "验证码已发送", Toast.LENGTH_SHORT).show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (time > 0) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    sendCode.setText(time + "s");
                                }
                            });
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            time--;
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                sendCode.setText("重新发送");
                            }
                        });
                        outdated = true;
                        time = 120;
                    }
                }).start();
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (realCheckCode.equals(checkCode.getText().toString()) && !outdated) {
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    RegisterStep2 step2 = RegisterStep2.newInstance();
                    fragmentTransaction.replace(R.id.step, step2);
                    fragmentTransaction.commit();
                } else if (!outdated) {
                    Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "验证码失效", Toast.LENGTH_SHORT).show();
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private static String generateCode() {
        int code = new Random().nextInt(900_000) + 100000;
        return String.valueOf(code);
    }

    private void findViews() {
        phone = findViewById(R.id.phone);
        checkCode = findViewById(R.id.checkCode);
        sendCode = findViewById(R.id.sendCode);
        next = findViewById(R.id.next_step);
        cancel = findViewById(R.id.cancel);
    }

    private boolean validatePhone(String phone) {
        return Pattern.matches("^1[0-9]{10}$", phone);
    }

    private boolean validateEmail(String email) {
        return Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", email);
    }
}